//
//  SearchFirstViewController.m
//  BiologyLibrary
//
//  Created by 朱进 on 16/7/4.
//  Copyright © 2016年 youxh. All rights reserved.
//

#import "SearchFirstViewController.h"
#import "ListCell.h"
#import "Record.h"
#import "NXfirststepViewController.h"

@implementation SearchFirstViewController

static NSString *strIdentifier_Cell                 = @"SearchFirstViewListTableCell";


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNaviBarTitle:self.recordName];
    // 创建一个自定义的按钮，并添加到导航条左侧。
    UIButton *btnNaviLeft = [CustomNaviBarView createImgNaviBarBtnByImgNormal:@"bar_left_image"
                                                                 imgHighlight:@"bar_left_image_f"
                                                                       target:self
                                                                       action:@selector(btnNaviLeftClick)];
    [self setNaviBarLeftBtn:btnNaviLeft];
    // 创建一个自定义的按钮，并添加到导航条右侧。
    UIButton*_btnNaviRight = [CustomNaviBarView
                              createNormalNaviBarBtnByTitle:@"筛选"
                              target:self
                              action:@selector(filterClick)];
    [self setNaviBarRightBtn:_btnNaviRight];
    
    _contentTableView = [[UITableView alloc] initWithFrame:
                         CGRectMake(0, fHeight_StatueBar + fHeight_Nav, fWidth_Current,
                                    fHeight_Current - fHeight_StatueBar - fHeight_Nav)];
    _contentTableView.backgroundColor = [UIColor clearColor];
    _contentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_contentTableView registerClass:[ListCell class]
              forCellReuseIdentifier:strIdentifier_Cell];
    _contentTableView.dataSource = self;
    _contentTableView.delegate = self;
    [self.view addSubview:_contentTableView];
    
    _searchVC = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchVC.hidesNavigationBarDuringPresentation = NO;
    _searchVC.dimsBackgroundDuringPresentation = NO;            //是否添加半透明覆盖层
    _searchVC.searchBar.frame = CGRectMake(0, 0, _contentTableView.frame.size.width, fHeight_Nav);
    _searchVC.searchResultsUpdater = self;
    
    _searchVC.searchBar.backgroundImage = [UIImage imageNamed:@"nav_image_bg"];
    for (UIView *tempView in [_searchVC.searchBar subviews]) {
        for (UIView *subView in [tempView subviews]) {
            if ([subView isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                subView.backgroundColor = [UIColor colorWithRed:0.24 green:0.27 blue:0.32 alpha:1];
                [subView setValue:[UIColor whiteColor]
                       forKeyPath:@"textColor"];
                [subView setValue:[UIColor whiteColor]
                       forKeyPath:@"_placeholderLabel.textColor"];
            }
        }
    }
    //不贴view下拉就会有阴影
    UIView *searchBarBackView = [[UIView alloc] initWithFrame:
                    CGRectMake(0, 64, _contentTableView.frame.size.width, fHeight_Nav)];
    [searchBarBackView addSubview:_searchVC.searchBar];
    searchBarBackView.backgroundColor=[UIColor clearColor];
    _contentTableView.tableHeaderView = searchBarBackView;
    
    _contentArray = [NSMutableArray array];
    _filterArray = [NSMutableArray array];
    
    _searchString = @"";
    _filterDateStr = @"";
    
    [self getData];
}

-(void)getData{
    
    [_contentArray removeAllObjects];
    [_filterArray removeAllObjects];
    
    _searchString = @"";
    _filterDateStr = @"";
    
    [self.view makeToastActivityWithMessage:@"获取列表"];
    self.view.userInteractionEnabled = NO;
    NSDictionary *parametersDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [APPUserDict objectForKey:@"userid"],@"userid",
                                    [NSString stringWithFormat:@"%ld",(long)self.recordType],@"sampleType",nil];
    NSLog(@"parametersDict %@",parametersDict);
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 15.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [manager POST:[NSString stringWithFormat:@"%@getSampleList.do",APPDelegate.baseUrl]
       parameters:parametersDict
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              self.view.userInteractionEnabled=YES;
              
              NSLog(@"responseObject %@",responseObject);
              if([responseObject isKindOfClass:[NSDictionary class]] && [[responseObject allKeys] containsObject:@"error"]){
                  [self.view hideToastActivityWithError:[responseObject objectForKey:@"error"] completion:nil];
                  return ;
              }

              NSArray *recordList = [NSArray arrayWithArray:responseObject];
              for (int i = 0; i < [recordList count]; i++) {
                  
                  NSMutableArray *tempDict = (NSMutableArray *)[recordList objectAtIndex:i];
                  NSDictionary*temp=(NSDictionary *)[tempDict objectAtIndex:0];
                  Record *record = [[Record alloc] init];
                  if (self.recordType==3) {
                      NSArray*addresslist=[temp objectForKey:@"addressList"];
                      if (addresslist.count>0) {
                          [record setAddressList:addresslist];
                      }
                      NSArray*cellsList=[temp objectForKey:@"cellsList"];
                      if (cellsList.count>0) {
                          [record setCellList:cellsList];
                      }
                      NSArray*nangYeList=[temp objectForKey:@"nangYeList"];
                      if (nangYeList.count>0) {
                          [record setNangshenmeList:nangYeList];
                      }
                  }else if(self.recordType==2||self.recordType==4||self.recordType==5){
                      NSArray*addresslist=[temp objectForKey:@"addressList"];
                      if (addresslist.count>0) {
                          [record setAddressList:addresslist];
                      }
                  }
                  
                  if (self.recordType == TYPE_RECORD_XUEYANGBEN ||
                      self.recordType == TYPE_RECORD_SHITIZHONGNIU ||
                      self.recordType == TYPE_RECORD_NANGXINGZHONGNIU)
                  {
                      if ([[temp objectForKey:@"informedCounsentName"] isKindOfClass:[NSString class]])
                      {
                          NSString *pathStr = [temp objectForKey:@"informedCounsentName"];
                          pathStr = [pathStr stringByReplacingOccurrencesOfString:@" " withString:@""];
                          pathStr = [pathStr stringByReplacingOccurrencesOfString:@"[" withString:@""];
                          pathStr = [pathStr stringByReplacingOccurrencesOfString:@"]" withString:@""];
                          NSArray *tempList = [pathStr componentsSeparatedByString:@","];
                          if ([tempList count] > 0)
                          {
                              NSMutableArray *imagePathList = [[NSMutableArray alloc] init];
                              for (NSString *path in tempList) {
                                  NSString *tempPathStr = [[NSString alloc] initWithFormat:@"http://%@",path];
                                  [imagePathList addObject:tempPathStr];
                              }
                              
                              [record setImagePathList:(NSArray *)imagePathList];
                          }
                      }
                  }
                  
                  record.recordId = [temp objectForKey:@"sampleNO"];
                  record.type = self.recordType;
                  record.name = self.recordName;
                  record.savedStepCount = self.allStepCount;
                  record.allStepCount = self.allStepCount;
                  record.creatTime = [[(NSDictionary *)[temp objectForKey:@"storeTime"] objectForKey:@"time"] integerValue] / 1000;
                  record.recordDetail = [[(NSDictionary *)[[temp objectForKey:@"record"] objectFromJSONString] objectForKey:@"record"] JSONString];
                  [_contentArray addObject:record];
                  [_filterArray addObject:record];
                  
                  NSLog(@"record === %@",record);
              }
              
              [_contentTableView reloadData];
              
              [self.view hideToastActivityWithCompletion:nil];
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              self.view.userInteractionEnabled=YES;
              
              DLog(@"operation %@",operation.responseString);
              if ([error code] == 1) {
                  
                  [self.view hideToastActivityWithError:d_Error_NetWork completion:nil];
              }else if([error code] == 2){
                  
                  [self.view hideToastActivityWithError:d_Error_TimeOut completion:nil];
              }else{
                  
                  [self.view hideToastActivityWithError:d_Error_UnKnow completion:nil];
              }
          }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [_filterArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ListCell *cell = [tableView dequeueReusableCellWithIdentifier:strIdentifier_Cell
                                                     forIndexPath:indexPath];
    
    Record *tempRecord = (Record *)[_filterArray objectAtIndex:indexPath.row];
    
    cell.titleLabel.text = tempRecord.recordId;
    cell.statusLabel.text = [NSString stringWithFormat:@"第%d步",tempRecord.savedStepCount];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        
    return g_fHeight_ListCell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    Record *tempRecord = (Record *)[_filterArray objectAtIndex:indexPath.row];
    tempRecord.savedStepCount = 0;
    [tempRecord setDetailDict:[NSMutableDictionary dictionaryWithDictionary:
                               [tempRecord.recordDetail objectFromJSONString]]];
    NXfirststepViewController *NXfirststepVC = [[NXfirststepViewController alloc] init];
    NSMutableArray <Record *>*nowArr=[[NSMutableArray alloc]init];
    [nowArr addObject:tempRecord];
    NXfirststepVC.NewRecordArray = nowArr;
    NXfirststepVC.fromtype = @"search";
    [self.navigationController pushViewController:NXfirststepVC animated:YES];
}

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    _searchString = [searchController.searchBar text];
    NSLog(@"_searchString %@",_searchString);
    
    [_filterArray removeAllObjects];
    for (Record *tempRecord in _contentArray) {
        
        if (([_filterDateStr isEqualToString:@""] ||
             [[TGCDataCenter getDateStringBySecondStr:[NSString stringWithFormat:@"%f",tempRecord.creatTime]
                                    withDateFormatter:@"YYYY-MM-dd"] isEqualToString:_filterDateStr]) &&
            ([_searchString isEqualToString:@""] || [tempRecord.recordId containsString:_searchString])) {
            tempRecord.savedStepCount = self.allStepCount;
            [_filterArray addObject:tempRecord];
        }
    }
    [_contentTableView reloadData];
}

-(void)btnNaviLeftClick{
    [_searchVC setActive:NO];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)filterClick{
    
    if (!_datePickAlertVC) {
        _datePickAlertVC = [UIAlertController alertControllerWithTitle:@"" message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];
        //初始化一个标题为“选择时间”，风格是ActionSheet的UIAlertController，其中"\n"是为了给DatePicker腾出空间
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            //点击确定按钮的事件处理
            _filterDateStr = [TGCDataCenter getDateStringBySecondStr:[NSString stringWithFormat:@"%f",[_datePicker.date timeIntervalSince1970]]
                                                   withDateFormatter:@"YYYY-MM-dd"];
            NSLog(@"_filterDateStr %@",_filterDateStr);

            [_filterArray removeAllObjects];
            for (Record *tempRecord in _contentArray) {
                
                NSLog(@"creatTime %@",[TGCDataCenter getDateStringBySecondStr:[NSString stringWithFormat:@"%f",tempRecord.creatTime]
                                                            withDateFormatter:@"YYYY-MM-dd"]);
                if (([_filterDateStr isEqualToString:@""] ||
                     [[TGCDataCenter getDateStringBySecondStr:[NSString stringWithFormat:@"%f",tempRecord.creatTime]
                                            withDateFormatter:@"YYYY-MM-dd"] isEqualToString:_filterDateStr]) &&
                    ([_searchString isEqualToString:@""] || [tempRecord.recordId containsString:_searchString])){
                    tempRecord.savedStepCount = self.allStepCount;
                    [_filterArray addObject:tempRecord];
                }
            }
            [_contentTableView reloadData];
        }];
        
        _datePicker = [[UIDatePicker alloc] init];//初始化一个UIDatePicker
        _datePicker.datePickerMode = UIDatePickerModeDate;
        [_datePickAlertVC.view addSubview:_datePicker];//将datePicker添加到UIAlertController实例中
        [_datePickAlertVC addAction:cancel];//将确定按钮添加到UIAlertController实例中
    }
    [self presentViewController:_datePickAlertVC animated:YES completion:^{
    }];//通过模态视图模式显示UIAlertController，相当于UIACtionSheet的show方法
}

@end
